//
//  CCImageCollectionView.m
//  Activity
//
//  Created by its on 15/5/12.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCImageCollectionView.h"
#import "CCImageCell.h"
#import <Masonry/Masonry.h>

#define DEFAULT_TAG  100

@interface CCImageCollectionView()
@property (nonatomic, weak) id<CCImageCollectionDataSource> dataSourece;
@end
@implementation CCImageCollectionView

- (id) initWithDataSourece:(id<CCImageCollectionDataSource>) dataSource {
  if (self = [super init]) {
    _numberOfColumns = 3;
    _columnGap = 4;
    _rowGap = 4;
    _dataSourece = dataSource;
    [self setupUI];
  }
  return self;
}

- (void) setupUI {
  _itemArray = [NSMutableArray arrayWithArray:[_dataSourece itemOfCollection]];
  for (int i = 0; i < _itemArray.count; i ++) {
    UIView *view = _itemArray[i];
    view.tag = i + DEFAULT_TAG;
    [self addSubview: view];
  }
}

- (void) layoutSubviews {
  CGFloat width = (CGRectGetWidth(self.frame) - _columnGap * (_numberOfColumns + 1)) / _numberOfColumns;
  for (int i = 0; i < _itemArray.count; i ++) {
    UIView *view = [self viewWithTag:i + DEFAULT_TAG];
    view.frame = CGRectMake((i%3)*width + (i%3) * _columnGap, (i/3)*width + (i/3) * _rowGap, width, width);
  }
  CGRect frame = self.frame;
  frame.size.height = width * (((_itemArray.count-1)/3) + 1) + _rowGap*(_itemArray.count/3);
//  self.frame = frame;
  [self mas_updateConstraints:^(MASConstraintMaker *make) {
    make.height.mas_equalTo(frame.size.height);
  }];
}

- (void) deleItem:(id)item {
  UIView *delview = item;
  NSInteger number = delview.tag - DEFAULT_TAG;
  [UIView animateWithDuration:0.2f animations:^{
    for (NSInteger i = number+1; i < _itemArray.count; i ++) {
      UIView *view = [self viewWithTag:i + DEFAULT_TAG];
      view.frame = [[self viewWithTag:i-1 + DEFAULT_TAG] frame];
    }
    for (NSInteger i = number+1; i < _itemArray.count; i ++) {
      UIView *view = [self viewWithTag:i + DEFAULT_TAG];
      view.tag = i-1 + DEFAULT_TAG;
    }
  } completion:^(BOOL finished) {
    [_itemArray removeObjectAtIndex:number];
  }];
  UIView *view = [self viewWithTag:number + DEFAULT_TAG];
  [view removeFromSuperview];
}

- (void) addItems:(NSArray *)items {
  int original = _itemArray.count;
  [_itemArray addObjectsFromArray: items];
  for (int i = original ; i < _itemArray.count; i ++) {
    UIView *view = _itemArray[i];
    view.tag = i + DEFAULT_TAG;
    [self addSubview: view];
  }

}
@end
